package com.woniuxy.controller;

import com.woniuxy.client.UserFeign;
import com.woniuxy.dto.CustomerApplicationDto;
import com.woniuxy.dto.CustomerApprovalDto;
import com.woniuxy.dto.CustomerProcessDto;
import com.woniuxy.entity.CustomerBasicInfo;
import com.woniuxy.service.CustomerApplicationService;
import com.woniuxy.service.CustomerBasicInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户申请管理Controller
 */
@Slf4j
@RestController
@RequestMapping("/api/customers")
@CrossOrigin(origins = "*")
public class CustomerApplicationController {

    @Autowired
    private CustomerApplicationService customerApplicationService;
    @Resource
    private CustomerBasicInfoService customerBasicInfoService;

    /**
     * 审批成功完成的回调，生成雪花id，修改状态
     */
    @GetMapping("/success")
    public void handleApproveSuccess(
            @RequestParam("processInstanceId") String processInstanceId, @RequestParam("customerCode") String customerCode) {
        customerBasicInfoService.newCustomerSuccess(processInstanceId, customerCode);

    }

    /**
     * 创建客户申请
     */
    @PostMapping
    public ResponseEntity<CustomerBasicInfo> createCustomerApplication(
            @Valid @RequestBody CustomerApplicationDto applicationDto,
            @RequestHeader(value = "X-User-Name", required = false, defaultValue = "admin") String currentUser) {

        log.info("创建客户申请，用户：{}", currentUser);
        CustomerBasicInfo customer = customerApplicationService.createCustomerApplication(applicationDto, currentUser);
        return ResponseEntity.ok(customer);
    }

    /**
     * 更新客户申请
     */
    @PutMapping("/{customerId}")
    public ResponseEntity<CustomerBasicInfo> updateCustomerApplication(
            @PathVariable Long customerId,
            @Valid @RequestBody CustomerApplicationDto applicationDto,
            @RequestHeader(value = "X-User-Name", required = false, defaultValue = "admin") String currentUser) {

        log.info("更新客户申请，客户ID：{}，用户：{}", customerId, currentUser);
        CustomerBasicInfo customer = customerApplicationService.updateCustomerApplication(customerId, applicationDto, currentUser);
        return ResponseEntity.ok(customer);
    }

    /**
     * 删除客户申请
     */
    @DeleteMapping("/{customerId}")
    public ResponseEntity<Void> deleteCustomerApplication(
            @PathVariable Long customerId,
            @RequestHeader(value = "X-User-Name", required = false, defaultValue = "admin") String currentUser) {

        log.info("删除客户申请，客户ID：{}，用户：{}", customerId, currentUser);
        customerApplicationService.deleteCustomerApplication(customerId, currentUser);
        return ResponseEntity.ok().build();
    }

    /**
     * 根据ID获取客户申请
     */
    @GetMapping("/{customerId}")
    public ResponseEntity<CustomerBasicInfo> getCustomerApplicationById(@PathVariable Long customerId) {
        log.info("获取客户申请，客户ID：{}", customerId);
        CustomerBasicInfo customer = customerApplicationService.getCustomerApplicationById(customerId);
        return ResponseEntity.ok(customer);
    }

    /**
     * 根据ID获取客户详情（包含所有相关信息）
     */
    @GetMapping("/{customerId}/detail")
    public ResponseEntity<com.woniuxy.dto.CustomerDetailDto> getCustomerDetailById(@PathVariable Long customerId) {
        log.info("获取客户详情，客户ID：{}", customerId);
        com.woniuxy.dto.CustomerDetailDto customerDetail = customerApplicationService.getCustomerDetailById(customerId);
        return ResponseEntity.ok(customerDetail);
    }

    /**
     * 分页查询客户申请
     */
    @GetMapping
    public ResponseEntity<Page<CustomerBasicInfo>> getCustomerApplications(
            Pageable pageable,
            @RequestParam(required = false) String customerName,
            @RequestParam(required = false) String approvalStatus,
            @RequestHeader(value = "X-User-Name", required = false, defaultValue = "system") String currentUser) {

        log.info("分页查询客户申请，用户：{}", currentUser);
        Page<CustomerBasicInfo> customers = customerApplicationService.getCustomerApplications(pageable, customerName, approvalStatus, currentUser);
        return ResponseEntity.ok(customers);
    }

    /**
     * 获取用户的客户申请列表
     */
    @GetMapping("/user")
    public ResponseEntity<List<CustomerBasicInfo>> getUserCustomerApplications(
            @RequestHeader("X-User-Name") String currentUser) {

        log.info("获取用户客户申请列表，用户：{}", currentUser);
        List<CustomerBasicInfo> customers = customerApplicationService.getUserCustomerApplications(currentUser);
        return ResponseEntity.ok(customers);
    }

    /**
     * 获取待审批客户列表
     */
    @GetMapping("/pending")
    public ResponseEntity<List<CustomerBasicInfo>> getPendingCustomerApplications(
            @RequestHeader("X-User-Name") String currentUser) {

        log.info("获取待审批客户列表，用户：{}", currentUser);
        List<CustomerBasicInfo> customers = customerApplicationService.getPendingCustomerApplications(currentUser);
        return ResponseEntity.ok(customers);
    }

    /**
     * 提交客户申请（启动工作流）
     */
    @PostMapping("/{customerId}/submit")
    public ResponseEntity<Map<String, String>> submitCustomerApplication(
            @PathVariable Long customerId,
            @RequestHeader("X-User-Name") String currentUser) {

        log.info("提交客户申请，客户ID：{}，用户：{}", customerId, currentUser);
        String processInstanceId = customerApplicationService.submitCustomerApplication(customerId, currentUser);

        Map<String, String> result = new HashMap<>();
        result.put("processInstanceId", processInstanceId);
        result.put("message", "客户申请提交成功，已启动审批流程");
        return ResponseEntity.ok(result);
    }

    /**
     * 通过客户申请
     */
    @PostMapping("/approve")
    public ResponseEntity<String> approveCustomer(
            @RequestParam("processInstanceId") String processInstanceId,
            @RequestHeader("X-User-Name") String currentUser) {
        customerApplicationService.approveCustomer(processInstanceId, currentUser);
        return ResponseEntity.ok(processInstanceId);
    }

    /**
     * 拒绝客户申请
     */
    @PostMapping("/reject")
    public ResponseEntity<String> approveCustomer(
            @RequestParam("processInstanceId") String processInstanceId,
            @RequestParam("reason") String reason,
            @RequestHeader("X-User-Name") String currentUser) {
        customerApplicationService.rejectCustomer(processInstanceId, reason, currentUser);
        return ResponseEntity.ok(processInstanceId);
    }

    /**
     * 获取我发起的 客户
     */
    @GetMapping("/getByCreateBy")
    public ResponseEntity<List<CustomerBasicInfo>> getByCreateBy(
            @RequestHeader("X-User-Name") String currentUser) {
        List<CustomerBasicInfo> customerBasicInfos = customerApplicationService.queryByCreateBy(currentUser);
        return ResponseEntity.ok(customerBasicInfos);
    }

    /**
     * 获取客户流程信息
     */
    @GetMapping("/{customerId}/process")
    public ResponseEntity<CustomerProcessDto> getCustomerProcess(@PathVariable Long customerId) {
        log.info("获取客户流程信息，客户ID：{}", customerId);
        CustomerProcessDto processDto = customerApplicationService.getCustomerProcess(customerId);
        return ResponseEntity.ok(processDto);
    }

    /**
     * 获取客户流程步骤
     */
    @GetMapping("/process/{processInstanceId}/steps")
    public ResponseEntity<List<CustomerProcessDto.ProcessStepDto>> getCustomerProcessSteps(
            @PathVariable String processInstanceId) {

        log.info("获取客户流程步骤，流程实例ID：{}", processInstanceId);
        List<CustomerProcessDto.ProcessStepDto> steps = customerApplicationService.getCustomerProcessSteps(processInstanceId);
        return ResponseEntity.ok(steps);
    }

    /**
     * 获取客户统计信息
     */
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getCustomerStatistics(
            @RequestHeader(value = "X-User-Name", required = false, defaultValue = "system") String currentUser) {

        log.info("获取客户统计信息，用户：{}", currentUser);
        Map<String, Object> statistics = customerApplicationService.getCustomerStatistics(currentUser);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 取消客户申请
     */
    @PostMapping("/{customerId}/cancel")
    public ResponseEntity<Map<String, String>> cancelCustomerApplication(
            @PathVariable Long customerId,
            @RequestParam String reason,
            @RequestHeader("X-User-Name") String currentUser) {

        log.info("取消客户申请，客户ID：{}，原因：{}，用户：{}", customerId, reason, currentUser);
        customerApplicationService.cancelCustomerApplication(customerId, reason, currentUser);

        Map<String, String> result = new HashMap<>();
        result.put("message", "客户申请已取消");
        return ResponseEntity.ok(result);
    }

    /**
     * 流程回调接口
     */
    @PostMapping("/callback")
    public ResponseEntity<Map<String, String>> handleProcessCallback(@RequestBody Map<String, Object> callbackData) {
        log.info("处理客户审批流程回调，数据：{}", callbackData);

        customerApplicationService.handleProcessCallback(callbackData);

        Map<String, String> result = new HashMap<>();
        result.put("message", "回调处理成功");
        return ResponseEntity.ok(result);
    }

    /**
     * 获取历史已审批的用户信息
     */
    @GetMapping("/history")
    public ResponseEntity<List<CustomerBasicInfo>> getHistoryCustomerApplications(@RequestHeader("X-User-Name") String currentUser) {
        List<CustomerBasicInfo> customers = customerApplicationService.getHistoryCustomerApplications(currentUser);
        return ResponseEntity.ok(customers);
    }
}
